package xyf.p04.tree;

import commons.TreeNode;

/**
 * ClassName: P0124_MaxSumPath
 * Description:
 * Author: xyf
 * Date: 9/8/22 6:12 PM
 * Version: 1.0
 **/
public class P0124_MaxSumPath
{
    private int max = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root)
    {
        dfs(root);
        return max;
    }

    private int dfs(TreeNode root)
    {
        if (root == null)
        {
            return 0;
        }

        int left = dfs(root.left);
        int right = dfs(root.right);

        if (left < 0)
        {
            left = 0;
        }
        if (right < 0)
        {
            right = 0;
        }
        max = Math.max(max, left + right + root.val);

        int maxSum = root.val;
        if (left > 0)
        {
            maxSum += left;
        }
        if (right > 0)
        {
            maxSum = Math.max(maxSum, right + root.val);
        }
        return maxSum;

    }
}
